package com.zjzywl.smoke.controller;

import java.io.File;
import java.net.URLDecoder;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zjzywl.smoke.config.AppConfig;
import com.zjzywl.smoke.entity.BuildingPeople;
import com.zjzywl.smoke.entity.BuildingPeopleSignin;
import com.zjzywl.smoke.util.BuildingPeopleList;
import com.zjzywl.smoke.util.WebResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "楼长管理", description = "楼长管理接口，提供楼长的增、删、改、查")
@RestController
@RequestMapping(value = "/buildingPeople")
public class BuildingPeopleController extends BaseController {
    @Autowired
    private AppConfig appConfig;

    @ApiOperation("小程序获取楼长列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "buildingPeopleId", value = "登陆小程序的用户id", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "operatingPost", value = "岗位 0单位楼长、1行政楼长、2街道消安办、3街道分管领导", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "buildingId", value = "岗位 0单位楼长、1行政楼长、2街道消安办、3街道分管领导", required = true, paramType = "query", dataType = "int")})

    @GetMapping("/getBuildingPeoplesWx")
    public WebResult<List<BuildingPeopleList>> getBuildingPeoplesWx(
            @RequestParam(value = "buildingPeopleId", required = false) Integer buildingPeopleId,
            HttpServletRequest request) throws Exception {
        try {
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/buildingPeople/getBuildingPeoplesWx?buildingPeopleId="
                            + buildingPeopleId + "&" + URLDecoder.decode(request.getQueryString(), "utf-8"),
                    Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 保存,修改巡更人员信息
    @RequestMapping(value = "/save/{orgId}", method = RequestMethod.POST)
    public WebResult save(BuildingPeople buildingPeople, @PathVariable("orgId") Integer orgId,
            @RequestParam(value = "workingRange", required = false) String workingRange, MultipartFile file)
            throws Exception {
        // try {

        if (file != null) {
            String headPortraitUrl = executeUpload(file);
            buildingPeople.setHeadPortraitUrl(headPortraitUrl);
        }
        ResponseEntity<BuildingPeople> entity = appConfig.restTemplate().postForEntity(
                appConfig.getGetDataIp() + "/buildingPeople/save/" + orgId, buildingPeople, BuildingPeople.class);
        return WebResult.OK(entity);
        // } catch (Exception e) {
        // return WebResult.FAIL(e.getMessage());
        // }
    }

    /*
     * 图片上传方法
     * 
     */
    private String executeUpload(MultipartFile file) throws Exception {
        String uploadDir = getUploadDir() + "building" + "/";
        // 如果文件不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("创建上传目录失败");
            }
        }
        if (file != null) {
            // 文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 上传文件名
            String filename = UUID.randomUUID() + suffix;
            // 服务器端保存的文件对象
            File serverFile = new File(uploadDir + filename);
            // 将上传到的文件写入到服务器
            file.transferTo(serverFile);
            return "/upload/" + "building" + "/" + filename;
        }
        return null;
    }

    // 删除巡更人员信息
    @DeleteMapping("/delete/{id}")
    public WebResult delete(@PathVariable("id") Integer id) {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/buildingPeople/delete/" + id);
            return WebResult.OK("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.getMessage());
        }
    }

    // 查询巡更人员信息
    @GetMapping("/getBuildingPeoples")
    public WebResult getBuildings(HttpServletRequest request) throws Exception {
        try {
            String userId = this.getUserId();
            System.out.println(appConfig.getGetDataIp() + "/buildingPeople/getBuildingPeoples?userId=" + userId + "&"
                    + URLDecoder.decode(request.getQueryString()));
            ResponseEntity<Object> entity = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/buildingPeople/getBuildingPeoples?userId=" + userId + "&"
                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 巡检人员登陆接口
    @PostMapping("/login")
    public WebResult login(@RequestParam("userName") String userName, @RequestParam("password") String password,@RequestParam("uuid") String uuid) {
        try {
            System.out.println(
                    appConfig.getGetDataIp() + "/buildingPeople/login?userName=" + userName + "&password=" + password);
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/buildingPeople/login?userName=" + userName + "&password=" + password+"&uuid="+uuid,
                    Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            String substring = e.toString().substring(e.toString().length()-8, e.toString().length()-5);
            if(substring.equals("406")) {
                WebResult webResult = new WebResult<>(Integer.parseInt(substring), e.toString());
                return webResult;
            }
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }
    }

    // 组织唯一性验证
    @RequestMapping(value = "/validateName")
    @ResponseBody
    public ResponseEntity<String> checkUserName(@PathParam("userName") String userName) {
        ResponseEntity<String> users = appConfig.restTemplate().postForEntity(
                appConfig.getGetDataIp() + "/buildingPeople/validateName?userName=" + userName, null, String.class);
        return users;
    }

    // Name唯一性监测 返回true为不重复，false为重复
    @RequestMapping(value = "/validateByName")
    @ResponseBody
    public ResponseEntity<String> validateByName(@RequestParam("name") String name) {
        ResponseEntity<String> users = appConfig.restTemplate().postForEntity(
                appConfig.getGetDataIp() + "/buildingPeople/validateByName?name=" + name, null, String.class);
        return users;
    }

    @ApiOperation("楼长签到")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lon", value = "楼长的经度", required = true, paramType = "query", dataType = "double"),
            @ApiImplicitParam(name = "lat", value = "楼长的纬度", required = true, paramType = "query", dataType = "double"),
            @ApiImplicitParam(name = "buildingPeopleId", value = "登陆小程序的用户id", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "uuid", value = "楼宇的唯一值", required = true, paramType = "query", dataType = "String") })
    @GetMapping("/signIn")
    @ResponseBody
    public WebResult<BuildingPeopleSignin> signIn(@RequestParam(value = "lon", required = false) double lon,
            @RequestParam(value = "lat", required = false) double lat,
            @RequestParam(value = "buildingPeopleId", required = false) Integer buildingPeopleId,
            @RequestParam(value = "uuid", required = false) String uuid) throws Exception {
        try {
            ResponseEntity<Object> history = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/buildingPeople/signIn?lon=" + lon + "&lat=" + lat
                            + "&buildingPeopleId=" + buildingPeopleId + "&uuid=" + uuid, Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            String substring = e.toString().substring(e.toString().length()-8, e.toString().length()-5);
            WebResult webResult = new WebResult<>(Integer.parseInt(substring), e.toString());
            return webResult;
        }
    }

    @ApiOperation("楼长签到列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "buildingPeopleId", value = "登陆小程序的用户id", required = true, paramType = "query", dataType = "int") })
    @GetMapping("/signInList")
    @ResponseBody
    public WebResult<List<BuildingPeopleSignin>> signInList(
            @RequestParam(value = "buildingPeopleId", required = false) Integer buildingPeopleId) throws Exception {
        try {
            ResponseEntity<Object> history = appConfig.restTemplate().getForEntity(
                    appConfig.getGetDataIp() + "/buildingPeople/signInList?&buildingPeopleId=" + buildingPeopleId,
                    Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            return WebResult.FAIL(e.toString());
        }
    }

    @ApiOperation("判断楼长今日是否重复签到   true为重复签到，false为没有重复签到")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "buildingPeopleId", value = "登陆小程序的用户id", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "buildingId", value = "楼宇的唯一值", required = true, paramType = "query", dataType = "int") })
    @GetMapping("/repeatSignIn")
    @ResponseBody
    public ResponseEntity<String> repeatSignIn(
            @RequestParam(value = "buildingPeopleId", required = false) Integer buildingPeopleId,
            @RequestParam(value = "uuid", required = false) String uuid) throws Exception {
        ResponseEntity<String> users = appConfig.restTemplate().postForEntity(appConfig.getGetDataIp()
                + "/buildingPeople/repeatSignIn?buildingPeopleId=" + buildingPeopleId + "&uuid=" + uuid, null,
                String.class);
        return users;
    }

}
